package com.begye.smartloan.apptest.signinup.ui

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import com.begye.smartloan.apptest.MyApplication
import com.begye.smartloan.apptest.R
import com.begye.smartloan.apptest.databinding.AtLoginBinding
import com.begye.smartloan.apptest.ext.addUnderLine
import com.begye.smartloan.apptest.fangkuanzhong.FangKuanZhongActivity
import com.begye.smartloan.apptest.gongong.YongHuLiuChengViewModel
import com.begye.smartloan.apptest.homeadsource.HomeAdSourceActivity
import com.begye.smartloan.apptest.homebefore.HomeBeforeActivity
import com.begye.smartloan.apptest.huankuan.HuanKuanActivity
import com.begye.smartloan.apptest.jujue.JuJueActivity
import com.begye.smartloan.apptest.shenhezhong.ShenHeZhongActivity
import com.begye.smartloan.apptest.tool.LoginTool
import com.begye.smartloan.apptest.tool.PageTagTool
import com.begye.smartloan.apptest.tool.SysConfigTool
import com.begye.smartloan.apptest.tool.addTouch
import com.begye.smartloan.apptest.xieyi.XieYiActivity
import com.util.utillib.extend.IntentFlagMode
import com.util.utillib.extend.afterTextChanged
import com.util.utillib.extend.toNextActivity
import org.json.JSONObject
import java.util.Timer
import java.util.TimerTask


@SuppressLint("CustomWelcomeScreen")
class SignInUpActivity : AppCompatActivity() {

    private lateinit var _binding: AtLoginBinding

    private var _timer = Timer()

    private val _signInUpViewModel by lazy {
        ViewModelProvider(this)[SignInUpViewModel::class.java]
    }

    private val _yongHuLiuChengViewModel by lazy {
        ViewModelProvider(this)[YongHuLiuChengViewModel::class.java]
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        LoginTool.updateLoginInfo(JSONObject())

        _binding = AtLoginBinding.inflate(layoutInflater)
        setContentView(_binding.root)

        configYongHuLiuChengState()
        configUIState()
        configUIEvent()
    }

    private fun configYongHuLiuChengState() {

        _signInUpViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onLoadingStateLiveData.observe(this) {
            if (it == true) {
                _binding.atGlobalLoading.show()
            } else {
                _binding.atGlobalLoading.hide()
            }
        }

        _yongHuLiuChengViewModel.onHasOrderStatusLiveData.observe(this) {
            it?.let { result ->
                when (result) {
                    PageTagTool.dai_huan_kuan -> {
                        toNextActivity(
                            activity = HuanKuanActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.fang_kuan_zhong -> {
                        toNextActivity(
                            activity = FangKuanZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.shen_he_zhone -> {
                        toNextActivity(
                            activity = ShenHeZhongActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }

                    PageTagTool.ju_jue -> {
                        toNextActivity(
                            activity = JuJueActivity::class.java,
                            mode = IntentFlagMode.SINGLE_TOP
                        )
                    }
                }
            }
        }

        _yongHuLiuChengViewModel.onAllDoneLiveData.observe(this) {
            it?.let { _ ->
                if (LoginTool.filterAdType()) {
                    toNextActivity(
                        activity = HomeAdSourceActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                } else {
                    toNextActivity(
                        activity = HomeBeforeActivity::class.java,
                        mode = IntentFlagMode.SINGLE_TOP
                    )
                }
            }
        }
    }

    private fun configUIState() {


        _signInUpViewModel.onCanStartTheCountdownLiveData.observe(this) {
            if (it) {
                startCodeLoop()
            }
        }

        _signInUpViewModel.onLoginSuccessfulLiveData.observe(this) {
            it?.let { _ ->
                _yongHuLiuChengViewModel.requestYongHuLiuCheng()
            }
        }
    }

    @SuppressLint("SetTextI18n")
    private fun configUIEvent() {

        _binding.atLoginPhCode.text = "+" + MyApplication.pCode

        _binding.atLoginPhNumber.afterTextChanged {
            updateCommitUIState()
        }

        _binding.atLoginDigitCode.afterTextChanged {
            updateCommitUIState()
        }

        _binding.atLoginDigitCodeReq.setOnClickListener {
            //
            addTouch(type = "sign_in_up_code_req_click")

            val phoneResult = checkPNumberUIState()
            if (phoneResult.isNotBlank()) {
                val accJsonObj = SysConfigTool.filterTestAccount(phoneResult)
                if (accJsonObj == null) {
                    _signInUpViewModel.requestToSendVerificationCode(phoneResult)
                } else {
                    LoginTool.updateLoginInfo(accJsonObj)
                    toNextActivity(
                        HomeBeforeActivity::class.java,
                        IntentFlagMode.SINGLE_TOP
                    )
                }
            }
        }

        _binding.atLoginCommit.setOnClickListener {
            //
            addTouch(type = "sign_in_up_commit_click")

            val phone = _binding.atLoginPhNumber.text.toString().trim()
            val code = _binding.atLoginDigitCode.text.toString().trim()

            val phoneResult = phone.replace(" ", "")
            val codeResult = code.replace(" ", "")

            if ((phoneResult.length >= 9) and (codeResult.length >= 4)) {
                val accJsonObj = SysConfigTool.filterTestAccount(phoneResult)
                if (accJsonObj == null) {
                    _signInUpViewModel.requestToLogin(
                        phone = phoneResult,
                        code = codeResult,
                        directLoginFlag = "NO"
                    )
                } else {
                    LoginTool.updateLoginInfo(accJsonObj)
                    toNextActivity(
                        HomeBeforeActivity::class.java,
                        IntentFlagMode.SINGLE_TOP
                    )
                }
            }
        }

        _binding.atLoginPrivacyCheckbox.setOnClickListener {
            _signInUpViewModel.agreePrivacyPolicy = !_signInUpViewModel.agreePrivacyPolicy
            if (_signInUpViewModel.agreePrivacyPolicy) {
                _binding.atLoginPrivacyCheckbox.setImageResource(R.drawable.dres_8)
            } else {
                _binding.atLoginPrivacyCheckbox.setImageResource(R.drawable.dres_7)
            }

            //
            addTouch(type = "sign_in_up_privacy_click")
        }

        _binding.atLoginPrivacyText.addUnderLine(getString(R.string.login_text_7), "#000000")
        _binding.atLoginPrivacyText.setOnClickListener {
            toNextActivity(
                XieYiActivity::class.java,
                IntentFlagMode.NEW_TASK
            )
        }
    }

    @SuppressLint("SetTextI18n")
    private fun startCodeLoop() {
        var curTick = 120

        _timer.cancel()
        _timer = Timer()
        _timer.schedule(object : TimerTask() {
            override fun run() {
                runOnUiThread {
                    _binding.atLoginDigitCodeReq.isEnabled = false
                    _binding.atLoginDigitCodeReq.text = "${curTick}s"
                    _binding.atLoginDigitCodeReq.setTextColor(Color.parseColor("#000000"))
                    _binding.atLoginDigitCodeReq.setBackgroundResource(R.drawable.layer_c28_dedede)
                    curTick -= 1
                    if (curTick == 0) {
                        _timer.cancel()
                        _binding.atLoginDigitCodeReq.setTextColor(Color.parseColor("#BEFF6A"))
                        _binding.atLoginDigitCodeReq.setBackgroundResource(R.drawable.layer_c25_000000)
                        _binding.atLoginDigitCodeReq.text = getString(R.string.login_text_4)
                        _binding.atLoginDigitCodeReq.isEnabled = true
                    }
                }
            }
        }, 0, 1000)
    }

    private fun checkPNumberUIState(): String {
        val phone = _binding.atLoginPhNumber.text.toString().trim()
        val phoneResult = phone.replace(" ", "")

        return if (phoneResult.length < 9) {
            _binding.atLoginPhNumberErrContent.visibility = View.VISIBLE
            _binding.atLoginPhNumberContent.setBackgroundResource(R.drawable.layer_c25_fafafa_err)
            ""

        } else {
            _binding.atLoginPhNumberErrContent.visibility = View.GONE
            _binding.atLoginPhNumberContent.setBackgroundResource(R.drawable.layer_c25_fafafa)
            phoneResult
        }
    }

    private fun updateCommitUIState() {
        val phone = _binding.atLoginPhNumber.text.toString().trim()
        val code = _binding.atLoginDigitCode.text.toString().trim()
        if (phone.length > 8 && code.length > 3) {
            _binding.atLoginCommit.isEnabled = true
            _binding.atLoginCommit.setTextColor(Color.parseColor("#BEFF6A"))
            _binding.atLoginCommit.setBackgroundResource(R.drawable.layer_c25_000000)
        } else {
            _binding.atLoginCommit.isEnabled = false
            _binding.atLoginCommit.setTextColor(Color.parseColor("#FFFFFF"))
            _binding.atLoginCommit.setBackgroundResource(R.drawable.layer_c25_dedede)
        }
    }

    override fun onResume() {
        super.onResume()

        addTouch(type = this.javaClass.simpleName, isOpen = true)
    }

    override fun onPause() {
        super.onPause()

        addTouch(type = this.javaClass.simpleName, isComplete = true)
    }
}

